<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;


use DB;
use Crypt;

class CygoodsController extends Controller
{
	/*************商品添加**************/ 
    public function addmain()
    {
    	// echo '1111';
    	$data = DB::table('cygoods')
    		-> select(['id','name','path', DB::raw('CONCAT(path,"-",id) AS sorpath')])
    		-> orderBy('sorpath', 'ASC')
    		-> get();
    	$b = array();
    	foreach($data as $k => $v)
    	{
    		$count = substr_count($v -> sorpath,'-');
    		$str = str_repeat('|----', $count);
    		$data[$k] -> name = $str.$v -> name;
    	}
    	// return view('admin.cygoods.addmain');
    	return view('admin.cygoods.addmain',['data' => $data]);
    }

    /************商品主类添加验证*************/
    public function insertmain(Request $request)

    {
        /*****************判断主类是否为空*******************/
    	$this -> validate($request,[
			'name' => 'required',
    		],[
			'name.required' => '商品主类不能为空',
    		]);

    	/*****************剔除字段*******************/
		$data = $request -> except('_token','id');
		// dd($data);
        /*****************查询商品*******************/
    	$res = DB::table('cygoods') -> where('name', $request -> input('name')) -> first();

        /*****************检查商品名是否重复*******************/
    	if($res)
    	{
			return redirect('/admin/cygoods/addmain') -> with(['info' => '主类名重复']);
    	}

    	/***************判断是否是根分类**************/
    	if($request -> input('id') == 0)
    	{
			$rres = DB::table('cygoods') -> insert($data);
    	}else{

	        /*****************查询父类的path*******************/
			$req = DB::table('cygoods') -> where('id', $request -> input('id')) -> first() -> path;
			// dd($req);

	        /*****************组合添加的path自动*******************/
			$data['path'] = $req.'-'.$request -> input('id');
			
			$data['pid'] = $request -> input('id');
			// dd($data);
	        /*****************执行添加命令*******************/
			$rres = DB::table('cygoods') -> insert($data);
    	}

		if($rres)
		{
			return redirect('/admin/cygoods/index') -> with(['info' => '添加成功']);
			// echo '111';
		}else{
			return redirect('/admin/cygoods/addmain') -> with(['info' => '添加失败']);
			// echo '222';
		}
    }

    /**********index主页遍历***********/
    public function index(Request $request)
    {
    	/*****************用户查询条数*******************/
    	// $num = $request -> input('num',10);
    	$data = DB::table('cygoods')
    		-> select(['id','name','path', DB::raw('CONCAT(path,"-",id) AS sorpath')])
    		-> orderBy('sorpath', 'ASC')
    		-> get();
    	// dd($request);

    	$dsgoods = DB::table('dsgoods')
    	-> where(function($query) use ($request)
    	{
    		$query -> where('name', 'like', '%'.$request -> input('keyword').'%');
    	})
    	-> get();

    	// $b = array();
    	// $c = 0;
    	// foreach($data as $ke => $v)
    	// {
    	// 	$b[$c] = $v -> pid;
    	// 	$c++;
    	// }
    	// $b = array_unique($b);

		foreach($data as $k => $v)
    	{

    		$users = DB::table('cygoods')
                     ->select(DB::raw('count(*) as count'))
                     ->where('pid', $v -> id)
                     ->get();

            $data[$k] -> count = $users[0] -> count;
    		// echo $users -> all();
    		// $data['count'] = $q1;
    		$count = substr_count($v -> path,'-');
    		$str = str_repeat('|----', $count);
    		$data[$k] -> name = $str.$v -> name;
    	}
    	foreach($data as $k => $v)
    	{

    		$users = DB::table('dsgoods')
                     ->select(DB::raw('count(*) as count1'))
                     ->where('pid', $v -> id)
                     ->get();

            $data[$k] -> count1 = $users[0] -> count1;
    	}
    	// foreach($data as $k => $v)
    	// {
    	// 	foreach($dsgoods as $k1 => $v1)
    	// 	{
    	// 		$arr1[$k] = $v;
    	// 		if($v -> id == $v1 -> pid)
    	// 		{
    	// 			$arr[$k1] = $v1;
    	// 		}
    	// 	}
    	// }
 
    	// dd($data);
    	return view('admin.cygoods.index',['data' => $data,'dsgoods' => $dsgoods, 'request' => $request -> all()]);

    }

/*****************商品添加*******************/
    public function adddsgoods(Request $request)
    {
    	$data1 = DB::table('cygoods')
    			-> select('pid')
    			-> get();
    	$b = array();
    	$c = 0;
    	foreach($data1 as $ke => $v)
    	{
    		$b[$c] = $v -> pid;
    		$c++;
    	}
    	$b = array_unique($b);
    	// dd($b);
    	$data = DB::table('cygoods')
    			-> whereNotIn('id',$b)
    			-> get();

    	// dd($data);
    		// echo 11;
    	return view('admin.cygoods.adddsgoods',['data' => $data]);

    }
/*****************商品添加处理*******************/
    public function insertgoods(Request $request)
    {
		$this -> validate($request,[
			'name' => 'required',
			'num' => 'required',
			'price' => 'required',
		],[
			'name.required' => '商品名称不能为空',
			'num.required' => '商品价格不能为空',
			'price.required' => '商品数量不能为空',
		]);

		$img1 = array('img1');
		$img1 = array_flip($img1);
		if(!in_array($data, $img1))
		{
			return redirect('/admin/cygoods/adddsgoods') -> with(['info' => '请上传商品图片']);
		}

		// 取出所有的键值
		$arr = array('name', 'parameter', 'pid', 'color', 'num' ,'price', 'content', 'introduce', 'sold');
		$data = $request -> except('_token');
		$data['color'] = $request -> goodscolor;
		$arr = array_flip($arr);
		// dd($data);
		$allowTypes = array('jpeg','jpg','png','gif');
    	$allowMime = array('image/jpeg','image/png','image/gif','image/jpg');
		$img = $_FILES;
		$string = null;
		// 遍历判断图片是否正确
		foreach($img as $k => $v)
		{
			if($v['size'] !== 0)
			{
				if($request -> hasFile($k))
				{
					if($request -> file($k) -> isValid())
					{
						$res = $request -> file($k) -> getClientOriginalExtension();
						$type = $request -> file($k) -> getClientMimeType();
						$error = $request -> file($k) -> getError();

						// 判断错误号
						switch($error){
				            case 1:
				            case 2:
				            case 3:
				            case 6:
				            case 7:
								return redirect('/admin/cygoods/adddsgoods') -> with(['info' => '系统内部错误']);
				                continue 2;
				            break;
				            case 4:
								return redirect('/admin/cygoods/adddsgoods') -> with(['info' => '没有文件被上传']);
				                continue 2;
				            break;
				        }

				        // 判断文件类型
						if(!in_array($type,$allowMime)){
							return redirect('/admin/cygoods/adddsgoods') -> with(['info' => '上传类型不符合']);
       					}

       					//判断后缀名名
       					if(!in_array($res,$allowTypes)){
							return redirect('/admin/cygoods/adddsgoods') -> with(['info' => '上传后缀名不对']);
					    }
					}
				}
			}
		}
		
		// 开始上传图片
		foreach($img as $k => $v)
		{
			if($v['size'] !== 0)
			{
				if($request -> file($k) -> isValid())
				{
					$res = $request -> file($k) -> getClientOriginalExtension();
					$type = $request -> file($k) -> getClientMimeType();
					$error = $request -> file($k) -> getError();
					$fileName = time() . rand(1,9).'.'.$res;
				    $request -> file($k) -> move('./img/goods/cygoods',$fileName);
				    if($string == null)
				    {
				    	$string .= $fileName;
				    }else{
				    	$string .= ','.$fileName;
				    }
				}
			}
		}

		$b = array();
		foreach($data as $k => $v)
		{
			if(array_key_exists($k,$arr))
			{
				$b[$k] = $v;
			}
		}
		$b['showpictures'] = $string;
		$b['time'] = date("Y-m-d H:i:s");
		// dd($b);
		$rres = DB::table('dsgoods') -> insert($b);
		if($rres)
		{
			return redirect('/admin/cygoods/index') -> with(['info' => '添加成功']);
		}else{
			return redirect('/admin/cygoods/adddsgoods') -> with(['info' => '添加失败']);
		}
		dd($b);
	}

	// 商品编辑修改
	public function edit($id)
	{
    	$data = DB::table('dsgoods') -> where('id', $id) -> first();
    	$img = $data -> showpictures;
    	// $data = substr_count($data,',');
    	$img = explode(',',$img);
    	// dd($img);
    	return view('admin.cygoods.edit',['data' => $data],['img' => $img]);
	}

	// 商品编辑修改
	public function update(Request $request)
	{
		$data = $request -> except('_token');

    	$res = DB::table('dsgoods') -> where('id', $request -> input('id')) -> update($data);
    	if($res)
    	{
        
            // dd($request);

    		 return redirect('/admin/cygoods/index') -> with(['info' => '更新成功']);
    	}else{
            // dd($request);
            
    		return back() -> with(['info' => '更新失败']);
   	 	}
	}

	// 商品删除
	public function delete($id)
	{
        $res = DB::table('cygoods') -> delete($id);

		if($res)
    	{
        
            // dd($request);

    		 return redirect('/admin/cygoods/index') -> with(['info' => '更新成功']);
    	}else{
            // dd($request);
            
    		return back() -> with(['info' => '更新失败']);
   	 	}
	}
}
